let config = require('../config/config.js')

// 调用高德API获取位置信息的示例函数
function getLocationInfo(latitude, longitude) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `https://restapi.amap.com/v3/geocode/regeo?key=${config.amap_key}&location=${longitude},${latitude}`,
			method: 'GET',
			success: (res) => {
				if (res.statusCode === 200 && res.data.status === '1') {
					resolve(res.data.regeocode);
				} else {
					reject(new Error('Failed to get location info'));
				}
			},
			fail: (error) => {
				reject(error);
			}
		});
	});
}

// 调用高德API解析经纬度
function getAddressByLatLng(latitude, longitude) {
	console.log(latitude, longitude,'getAddressByLatLng');
	const url = `https://restapi.amap.com/v3/geocode/regeo?key=${config.amap_key}&location=${longitude},${latitude}&radius=1000&extensions=all&roadlevel=0`;
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'GET',
			success: (res) => {
				if (res.statusCode === 200 && res.data.status === '1') {
					// 成功获取地址信息
					resolve(res.data.regeocode)
					console.log('获取地址',res.data.regeocode);
				} else {
					// 错误处理
					reject(res.data)
					console.error('获取地址失败', res.data);
				}
			},
			fail: (error) => {
				// 请求失败处理
				reject(error)
				console.error('请求失败', error);
			}
		});
	});
}

// 调用高德API解析地址
function getAddressByAddress(address,city) {
	console.log(address,city,'getAddressByAddress');
	const url = `https://restapi.amap.com/v3/geocode/geo?key=${config.amap_key}&address=${address}&city=${city}`;
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'GET',
			success: (res) => {
				if (res.statusCode === 200 && res.data.status === '1') {
					// 成功获取地址信息
					resolve(res.data.geocodes)
					console.log('获取地址',res.data.geocodes);
				} else {
					// 错误处理
					reject(res.data)
					console.error('获取地址失败', res.data);
				}
			},
			fail: (error) => {
				// 请求失败处理
				reject(error)
				console.error('请求失败', error);
			}
		});
	});
}
// 导出http方法
module.exports = {
	getLocationInfo,
	getAddressByLatLng,
	getAddressByAddress
}